package com.gin.kotlin.gf2gamecommunity.routes

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.rounded.DateRange
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.Badge
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import coil3.compose.AsyncImage
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.composable.HorizontalPagerIndex
import com.gin.kotlin.gf2gamecommunity.base.composable.PageState
import com.gin.kotlin.gf2gamecommunity.base.composable.SimpleAlertDialog
import com.gin.kotlin.gf2gamecommunity.composable.LoginDialog
import com.gin.kotlin.gf2gamecommunity.composable.MessageIconButton
import com.gin.kotlin.gf2gamecommunity.composable.OpenLinkButton
import com.gin.kotlin.gf2gamecommunity.composable.index.IndexCommunity
import com.gin.kotlin.gf2gamecommunity.composable.index.IndexDaily
import com.gin.kotlin.gf2gamecommunity.composable.index.IndexSettings
import com.gin.kotlin.gf2gamecommunity.navi.GF2Navigator
import com.gin.kotlin.gf2gamecommunity.viewmodel.DailyViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.ExchangeItemViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.MessageViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.UserViewModel
import kotlinx.coroutines.delay
import kotlinx.serialization.Serializable
import retrofit2.awaitResponse

/**
 * 扩展方法
 * @receiver [NavGraphBuilder]
 * @param onNavigateToTopicList 导航到主题列表
 */
fun NavGraphBuilder.index(
    messageViewModel: MessageViewModel,
    navigator: GF2Navigator
) = composable<IndexRoute> {
    IndexComposable(navigator = navigator, route = it.toRoute(), messageViewModel = messageViewModel)
}

/**
 * 首页路线
 * @param initialIndex 导航栏的初始位置
 * @constructor
 */
@Serializable
data class IndexRoute(val initialIndex: Int = 1)

/**
 * 首页组件
 * @param route IndexRoute 路线
 * @param onNavigateToTopicList 导航到主题列表
 */
@Composable
fun IndexComposable(navigator: GF2Navigator, route: IndexRoute = IndexRoute(), messageViewModel: MessageViewModel = viewModel()) {
    navigator.apply {
        // 路由配置
        val states = listOf(
            PageState("日常", { Icon(Icons.Rounded.DateRange, contentDescription = null) }, {
                IndexDaily(onNavigateToExchangeItem = { onNavigateToExchangeItem(it) }, onNavigateToScoreLog = { onNavigateToScoreLog(it) })
            }),
            PageState("社区", { Icon(Icons.Rounded.Home, contentDescription = null) }, {
                IndexCommunity(navigator = navigator)
            }),
            PageState("配置", { Icon(Icons.Rounded.Settings, contentDescription = null) }, {
                IndexSettings()
            }),
        )

        // 抽屉式导航栏
        HorizontalPagerIndex(states = states,
            initialIndex = route.initialIndex,
            actions = {
                OpenLinkButton(navigator)
                MessageIconButton({ onNavigateToMessageList(it) }, messageViewModel)
                IconButton(onClick = { onNavigateToSearch(SearchRoute()) }) {
                    Icon(imageVector = Icons.Filled.Search, contentDescription = "搜索")
                }
            },
            drawerSheetContent = {
                DrawerContent(onNavigateToAccountManage = { onNavigateToAccountManage(it) },
                    messageViewModel = messageViewModel,
                    onNavigateToUserCenter = { onNavigateToUserCenter(it) },
                    onNavigateToMessageList = { onNavigateToMessageList(it) })
            })

        AutoScript()
    }

}

@Composable
private fun AutoScript(
    userViewModel: UserViewModel = viewModel(),
    dailyViewModel: DailyViewModel = viewModel(),
    exchangeItemViewModel: ExchangeItemViewModel = viewModel(),
) {
    val messages = remember { mutableStateListOf<String>() }
    var showAlertDialog by remember { mutableStateOf(false) }
    val tag = "AutoScript"
    val userInfoState = userViewModel.cUser.liveData.observeAsState()
    // 当前账号
    val account = App.INSTANCE.currentAccount() ?: return
    LaunchedEffect(userInfoState.value) {
        val userInfo = userInfoState.value ?: return@LaunchedEffect
        Log.i(tag, "自动脚本开始: ${userInfo.nickName}")

        if (account.autoSignIn) {
            val script = "<自动签到>"
            Log.i(tag, script)
            dailyViewModel.apply {
                try {
                    if (current.fetchAwait()?.hasSignIn == false) {
                        try {
                            // 执行成功
                            val response = dailyViewModel.signInCall().awaitResponse()
                            // 打开对话框
                            showAlertDialog = true
                            // 异步更新签到状态
                            current.fetch(true)
                            // 添加消息
                            messages.add("$script: 成功-> ${response.body()?.message ?: response.message()}")

                            delay(200)
                        } catch (e: Exception) {
                            e.printStackTrace()
                            messages.add("$script: 失败-> ${e.message}")
                        }
                    } else {
                        messages.add("$script: 今天已签到")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    messages.add("$script: 失败-> ${e.message}")
                }
            }
        }

        if (account.autoDailyTask) {
            val script = "<自动日常>"
            Log.i(tag, script)
            dailyViewModel.apply {
                try {
                    val dailyTask = tasks.fetchAwait()?.dailyTask?.filter { !it.completed() }
                    // 打开对话框
                    if (dailyTask.isNullOrEmpty()) {
                        messages.add("$script: 任务已全部完成")
                    } else {
                        showAlertDialog = true
                        // 执行日常任务
                        dailyAll { messages.add("$script $it") }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    messages.add("$script: 失败-> ${e.message}")
                }
            }
        }

        if (account.autoExchange) {
            val script = "<自动兑换>"
            Log.i(tag, script)
            exchangeItemViewModel.apply {
                val itemList = exchangeList.fetchAwait()?.filter { it.exchangeable() }?.takeIf { it.isNotEmpty() }
                delay(200)
                val sumPrice = itemList?.sumOf { (it.exchangeableCount()) * it.useScore } ?: 0
                when {
                    itemList.isNullOrEmpty() -> messages.add("$script: 已兑换全部道具")
                    userInfo.score < sumPrice -> {
                        showAlertDialog = true
                        messages.add("$script: 积分不足, 请手动兑换")
                    }
                    // 自动兑换
                    else -> {
                        showAlertDialog = true
                        exchangeAll(itemList) { item, _ -> messages.add("$script: 兑换成功-> ${item.itemName}") }
                    }
                }

            }
        }
    }


    when {
        showAlertDialog -> {
            SimpleAlertDialog(onDismissRequest = {
                showAlertDialog = false
                // 关闭时更新用户信息
                userViewModel.cUser.fetch(true)
            }) {
                Text("自动任务", fontSize = 22.sp, fontWeight = FontWeight.Bold)
                LazyColumn { items(items = messages) { Text(it) } }
            }
        }
    }
}


/**
 * 抽屉内容
 */
@Composable
private fun DrawerContent(
    viewModel: UserViewModel = viewModel(),
    messageViewModel: MessageViewModel = viewModel(),
    onNavigateToAccountManage: (route: AccountManageRoute) -> Unit,
    onNavigateToUserCenter: (UserCenterRoute) -> Unit,
    onNavigateToMessageList: (route: MessageListRoute) -> Unit
) {
    // 对话框的打开状态
    val openLoginDialog = remember { mutableStateOf(false) }

    val userInfoState = viewModel.cUser.liveData.observeAsState()
    val unreadCountState = messageViewModel.unreadCount.liveData.observeAsState()


    val account = App.INSTANCE.currentAccount()

    if (account != null) {
        messageViewModel.unreadCount.fetch()
        viewModel.fetchCurrentUserInfo()
    }

    Column {
        // 当前用户头像和昵称
        Box(modifier = Modifier.fillMaxWidth()) {
            userInfoState.value?.apply {
                Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier
                    .fillMaxWidth()
                    .clickable {
                        onNavigateToUserCenter(UserCenterRoute(uid))
                    }) {
                    AsyncImage(model = avatar, contentDescription = null, modifier = Modifier
                        .clip(CircleShape)
                        .size(120.dp))
                    Text(nickName, modifier = Modifier.padding(16.dp))
                }
            } ?:
            // 无用户信息 显示占位头像 点击打开对话框登录
            Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
                Icon(imageVector = Icons.Filled.Person, contentDescription = "占位头像", modifier = Modifier
                    .size(120.dp)
                    .clickable { openLoginDialog.value = true })
                Text("点击登录", modifier = Modifier
                    .padding(16.dp)
                    .clickable { openLoginDialog.value = true })
            }
        }
        // 横向分割线
        HorizontalDivider(Modifier.height(2.dp))

        NavigationDrawerItem(icon = { Icon(imageVector = Icons.Filled.Person, contentDescription = "个人中心") }, label = { Text("个人中心") }, selected = false,
            onClick = {
                userInfoState.value?.apply {
                    onNavigateToUserCenter(UserCenterRoute(uid))
                }
            })

        NavigationDrawerItem(icon = { Icon(imageVector = Icons.Filled.AccountBox, contentDescription = "账号管理") }, label = { Text("账号管理") }, selected = false,
            onClick = { onNavigateToAccountManage(AccountManageRoute()) })

        NavigationDrawerItem(icon = { Icon(imageVector = Icons.Filled.Email, contentDescription = "消息") }, label = {
            Row(horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                Text("消息")
                unreadCountState.value?.total()?.takeIf { it > 0 }?.also { total -> Badge(content = { Text(total.toString()) }) }
            }
        }, selected = false, onClick = { onNavigateToMessageList(MessageListRoute()) })
    }

    // 当 openLoginDialog 为 true时打开登录对话框
    when {
        openLoginDialog.value -> LoginDialog(onSuccess = { _, _, _ -> openLoginDialog.value = false }, onCloseDialog = { openLoginDialog.value = false })
    }
}

